import React, { Component } from 'react'
import normalizeSearch from '../util/normalizeSearch'
import { checkObjRequired, extendArrayMinus, batchBindThis } from 'util/common.js'
import WarnModal from 'util/warnModal.js'
import { Select, Row, Col, Table, Button, Modal, Input, message } from 'antd'
import './css/positionAndLevel.css'
import CanDelDiv from 'util/canDelDiv.js'
extendArrayMinus()
class positionAndLevel extends Component{
    constructor(props) {
        super(props)
        this.state = {
            companyList: [],
            versionList: [],
            detail: [],
            company: '',
            addSelectShowIndex: -1,
            addValue: '',
            addModeFlag: false,
            addJobModelVisible: false,
            newJobObj: { jobName: '', hierarchyNameSet: []},
            version: '',
            deleteModalVisible: false,
            deleteName: '',
            hasHierachy: [],
            addJobHierarchyMode: false
        }
        batchBindThis(this, 'addSelectChange', 'addJobModelShow', 'addJobConfirm', 'addJobCancel', 'findVersionChange', 'findCompanyChange', 'deleteOk', 'deleteCancel', 'modifyAddModeChange', 'submitEdit', 'delHierarchyOfJob')
    }
    submitEdit() {
        const { company, detail, versionList, addJobHierarchyMode } = this.state
        const params = { company, data: detail, lastVersion: versionList[0]}
        const requestUrl = addJobHierarchyMode ? '/snail/jobsHierarchy/saveJobsHierachyBigVersion' : '/snail/jobsHierarchy/saveJobsHierachySmallVersion'
        fetch(requestUrl, {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(params)
        }).then(
            res => res.json()
        ).then((data) => {
            if ( data.code === 200 ) {
                addJobHierarchyMode ? message.success('添加版本成功') : message.success('修改版本成功')
            }
        })
    }
    deletePosition(index, job) {
        this.setState({
            deleteModalVisible: true,
            deleteIndex: index,
            deleteName: job
        })
    }
    deleteOk() {
        const { detail, deleteIndex } = this.state
        this.setState({
            detail: detail.filter((item, index) => {
                return index !== deleteIndex
            }),
            deleteModalVisible: false,
            deleteName: ''
        })
    }
    deleteCancel() {
        this.setState({
            deleteModalVisible: false
        })
    }
    _findVersionByCompany = (company) => {
        return fetch('/snail/jobsHierarchy/findVersionByCompany', {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ company })
        }).then(
            res => res.json()
        )
    }
    findCompanyChange(value) {
        this.setState({
            company: value,
            version: ''
        })
        this._findVersionByCompany(value).then(this.changeCompanyUpdateJobHierarachy)
    }
    findVersionChange(value) {
        const positionVersion = value
        const company = this.state.company
        this._findAllJobsHierarchy({positionVersion, company}).then((data) => {
            this.setState({
                detail : data.data,
                version: value
            })
        })
    }
    addSelectChange() {
        return value => {
            this.setState({
                addValue: value
            })
        }
    }
    confirmAddNewHierarchy(index) {
        const { detail, addValue } = this.state
        const newDetail = detail.map((item, i) => {
            if (index === i) {
                return {...item, hierarchyNameSet: item.hierarchyNameSet.concat(addValue), restHierarchy: item.restHierarchy.minus(addValue)}
            }else {
                return item
            }
        })
        this.setState({
            addModeFlag: false,
            detail: newDetail,
            addValue: ''
        })
    }
    cancelAddNewHierarchy() {
        this.setState({
            addModeFlag: false,
            addValue: ''
        })
    }
    addNewHierarchy(index) {
        this.setState({
            addValue: '',
            addModeFlag: true,
            addSelectShowIndex: index
        })
    }
    delHierarchyOfJob(index) {
        return (v) => {
            this.setState({
                detail: this.state.detail.map((item, i) => {
                    let obj = i !== index ? item : {...item, hierarchyNameSet: item.hierarchyNameSet.filter((item, _index) => {
                            return _index !== v
                        })}
                    return obj
                })
            })
        }
    }
    columns = [{
        title: '岗位',
        dataIndex: 'jobName',
        key: 'jobName',
    }, {
        title: '层级',
        className: 'hierarchy-title',
        dataIndex: 'hierarchyName',
        key: 'hierarchyName',
        render: (text, record, index) => {
            const { addSelectShowIndex, addValue, addModeFlag, addJobHierarchyMode } = this.state
            const { hierarchyNameSet, restHierarchy } = record
            return (
                <div>
                    <CanDelDiv data={hierarchyNameSet} canDel={addJobHierarchyMode} onChange={this.delHierarchyOfJob(index)}/>
                    <Select value={addValue} style={{ width: 120 }} placeholder="请选择" onChange={this.addSelectChange()} className={addSelectShowIndex === index && addModeFlag ? 'visible' : 'hidden'}>
                        {
                            restHierarchy.map((item) => {
                                return (
                                    <Option value={item} key={item}>{item}</Option>
                                )
                            })
                        }
                    </Select>
                </div>
            )
        }
    }, {
        title: '修改',
        dataIndex: 'flag',
        key: 'flag',
        render: (text, record, index) => {
            const { addModeFlag, addSelectShowIndex, addJobHierarchyMode } = this.state
            return (
                <div>
                    <Button onClick={this.addNewHierarchy.bind(this, index)} disabled={!record.restHierarchy.length} className={addModeFlag && index === addSelectShowIndex ? 'ant-btn-link none' : 'ant-btn-link block'}>新增</Button>
                    <Button onClick={this.confirmAddNewHierarchy.bind(this, index)} className={ addModeFlag && index === addSelectShowIndex ? 'ant-btn-link block' : 'ant-btn-link none'}>确定</Button>
                    <Button onClick={this.cancelAddNewHierarchy.bind(this, index)} className={ addModeFlag && index === addSelectShowIndex ? 'ant-btn-link block' : 'ant-btn-link none'}>取消</Button>
                    <Button onClick={this.deletePosition.bind(this, index, record.jobName)} disabled={!(record.flag || addJobHierarchyMode)} className="ant-btn-link">删除</Button>
                </div>
            )
        }
    }]
    _selectComp = (theState, theseState, func) => {
        const state = this.state[theState]
        const stateList = this.state[theseState]
        return (
            <Select
                showSearch
                style={{ width: 200 }}
                optionFilterProp="children"
                // defaultValue={state[0]}
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                onChange={ func }
                value={state}
            >
                {
                    stateList.map((item) => {
                        return (<Option value={item} key={item}>{item}</Option>)
                    })
                }
            </Select>
        )
    }
    _findAllJobsHierarchy = (obj) => {
        return fetch('/snail/jobsHierarchy/findJobsHierarchyByCondition', {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(obj)
        }).then(
            res => res.json()
        )
    }
    addJobModelShow() {
        this.setState({
            addJobModelVisible: true
        })
    }
    addJobConfirm() {
        const { newJobObj, detail } = this.state
        if (checkObjRequired(newJobObj)){
            const newJobObjPlus = {...newJobObj, flag: true, restHierarchy: this.state.hasHierachy.filter((item) => !newJobObj.hierarchyNameSet.includes(item))}
            this.setState({
                detail: detail.concat(newJobObjPlus),
                addJobModelVisible: false
            })
        }
    }
    addJobCancel() {
        this.setState({
            addJobModelVisible: false
        })
    }
    changeCompanyUpdateJobHierarachy = (data) => {
        const { company } = this.state
        this.setState({
                          versionList: data.data,
                          version: data.data[0]
        }, () => {
            const positionVersion = this.state.version
            this._findAllJobsHierarchy({positionVersion, company}).then((data) => {
                this.setState({
                    detail : data.data
                })
            })
        })
    }
    searchHierarchyByJob = (jobName) => {
        fetch('/snail/jobsHierarchy/findAllHierachyByJobName', {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ jobName })
        }).then(
            res => res.json()
        ).then((data) => {
            this.setState({
                hasHierachy: data.data
            })
        })
    }
    modifyAddModeChange(value) {
        const addJobHierarchyMode = value === 'add'
        this.setState({
            addJobHierarchyMode
        })
        const { version, company } = this.state
        this._findAllJobsHierarchy({positionVersion: version, company}).then((data) => {
            this.setState({
                detail : data.data
            })
        })
    }
    componentDidMount() {
        fetch('/snail/jobsHierarchy/findAllCompany').then(
            res => res.json()
        ).then((data) => {
            this.setState({
                companyList: data.data,
                company: data.data[0]
            }, () => {
                const { company } = this.state
                this._findVersionByCompany( company ).then(this.changeCompanyUpdateJobHierarachy)
            })
        })
    }
    render() {
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const { newJobObj, deleteModalVisible, deleteName, hasHierachy } = this.state
        return (
            <div>
                <WarnModal visible={deleteModalVisible} onOk={this.deleteOk} onCancel={this.deleteCancel} deleteName={deleteName}></WarnModal>
                {this.state.companyList.length && this.state.versionList.length ?
                    <Row>
                        <Col span={3}><span className="col-span">业务方：</span></Col>
                        <Col span={6}>{this._selectComp('company', 'companyList', this.findCompanyChange)}</Col>
                        <Col span={3}><span className="col-span">版本：</span></Col>
                        <Col span={6}>{this._selectComp('version', 'versionList', this.findVersionChange)}</Col>
                    </Row>
                    :null}
                <Row>
                    <Col span={18}><Button type="primary" onClick={this.addJobModelShow} style={{marginTop: 10}}>新增岗位</Button></Col>
                    <Col span={4}>
                        {/*<Button type="primary" onClick={this.editJobHierarchy} style={{marginTop: 10, marginRight: 10}}>修改岗位层级</Button>*/}
                        {/*<Button type="primary" onClick={this.addJobHierarchy} style={{marginTop: 10}}>新增岗位层级</Button>*/}
                        <Select defaultValue="modify" style={{ width: '100%' }} onChange={this.modifyAddModeChange}>
                            <Option value="modify">修改岗位层级</Option>
                            <Option value="add">新增岗位层级</Option>
                        </Select>
                    </Col>
                    <Col span={2}>
                        <Button type="primary" onClick={this.submitEdit}>提交</Button>
                    </Col>
                </Row>

                <Table style={{paddingTop: 10}} columns={this.columns} dataSource={this.state.detail} />
                <Modal
                    title="新增岗位"
                    visible={this.state.addJobModelVisible}
                    onOk={this.addJobConfirm}
                    onCancel={this.addJobCancel}
                >
                    <Row>
                        <Col span={6}>岗位</Col>
                        <Col span={12}><Input onBlur={(e) => {this.setState({newJobObj: {...newJobObj, jobName: e.target.value}}, () => {
                            this.searchHierarchyByJob(this.state.newJobObj.jobName)
                        });}}/></Col>
                    </Row>
                    <Row>
                        <Col span={6}>层级</Col>
                        <Col span={12}><Select
                            mode="multiple"
                            onChange={(value) => {this.setState({newJobObj: {...newJobObj, hierarchyNameSet: value}})}}
                            style={{width: '100%'}}
                            // value={this.state.addJobOfHierarchy}
                        >
                            {hasHierachy.map((item) => {
                                return (
                                    <Option value={item} key={item}>{item}</Option>
                                )
                            })}
                        </Select></Col>
                    </Row>
                </Modal>
            </div>

        )
    }
}
export default positionAndLevel